import { ref } from 'vue'
import directory_treeData from '../data/sceneModelsData.js'
import { MainModelData, modelPos } from '@/views/data/MainModelData.js'
import {
  ArmData,
  agvData,
  xingjiaType01Data,
  xingjiaType02Data,
  xingjiaTypeTempData,
  GTYXData,
  PogoData
} from '@/views/data/DeviceData.js'
import {
  InitSocket,
  getCollectData,
  updatedhandleData,
  ArmDataMap,
  AGVDataMap,
  XJDataMap,
  XJDataMap2,
  XJDataMapTemp,
  GYTXDataMap,
  PogoDataMap,
  socket,
  Create3DLable,
  destroyAllModels
} from '@/views/js/DataManger.js'
import { getInfoFuzzy } from '@/api/CollectRequest.js'
import XJPostionData from '@/views/data/XJPostionData.js'
let models = []
let modelUrls = []
let outLine, outLine2
let currentSelectModel
let boxHelper = null
let boxEffect = null
const GeometryError = 2
let handleModel
const articulations = ref([])
const AllModelTypeMap = new Map() // 存储已加载的模型
const loadingPromises = new Map() // 存储正在加载的Promise
const sceneModelMap = new Map()//  存储场景模型分类

// 在全局或模块作用域中创建Map来存储LOD对象
const lodMap = new Map()

function InitScene (DeviceClickcallBack, socketCallBack) {
  outLine = new GCMap.OutLine2({
    sandbox: window.sandbox,
    color: 0xe91010
  })
  outLine2 = new GCMap.OutLine2({
    sandbox: window.sandbox,
    color: 0x00ffff
  })

  SetControls()
  OnShadow()
  loadMainmodel(DeviceClickcallBack, socketCallBack)
}
function OnShadow () {
  const posCtrl = { x: 6.6, y: 100, z: 14 } // 初始值
  const lightIntensity = { intensity: 4 }
  const lightIntensity2 = { intensity: 2 }
  const ambient = new GC.AmbientLight(0xffffff, lightIntensity2.intensity)
  window.sandbox.scene.add(ambient)
  models.push(ambient)

  const directionalLight = new GC.DirectionalLight(0xffffff, lightIntensity.intensity)
  models.push(directionalLight)
  window.sandbox.scene.add(directionalLight)
  window.sandbox.renderer.shadowMap.enabled = true // 启用阴影
  window.sandbox.renderer.shadowMap.type = GC.PCFSoftShadowMap // 更柔和的阴影（可选）

  directionalLight.castShadow = true // 启用光源阴影
  directionalLight.position.set(posCtrl.x, posCtrl.y, posCtrl.z)
  // addTransformControlsMesh02(directionalLight);

  // 调整阴影参数（优化阴影质量）
  directionalLight.shadow.mapSize.width = 2048 // 阴影贴图分辨率
  directionalLight.shadow.mapSize.height = 2048
  directionalLight.shadow.camera.near = 0.01 // 阴影计算范围
  directionalLight.shadow.camera.far = 5000

  const distance = 60
  directionalLight.shadow.camera.left = -distance
  directionalLight.shadow.camera.right = distance
  directionalLight.shadow.camera.top = distance
  directionalLight.shadow.camera.bottom = -distance

  // const gui = new GC.GUI()
  // const axisArray = ['x', 'y', 'z']
  // axisArray.forEach(axis =>
  //   gui.add(posCtrl, axis, -100, 100, 0.1)
  //     .name(`Light ${axis.toUpperCase()}`)
  //     .onChange(v => directionalLight.position[axis] = v)
  // )

  // gui.add(lightIntensity, 'intensity', 0, 10, 0.01) // 最小 0，最大 5，步长 0.01
  //   .name('Light intensity')
  //   .onChange(val => {
  //     directionalLight.intensity = val // 实时同步给光源
  //   })
  // gui.add(lightIntensity2, 'intensity', 0, 10, 0.01) // 最小 0，最大 5，步长 0.01
  //   .name('ambient intensity')
  //   .onChange(val => {
  //     ambient.intensity = val // 实时同步给光源
  //   })

  // const shadowHelper = new GC.CameraHelper(directionalLight.shadow.camera);
  // scene.add(shadowHelper); //
}

// 加载场景主要模型
async function loadMainmodel (DeviceClickcallBack, socketCallBack) {
  await loadSimpleModels(MainModelData)

  await loadAllModels(ArmData, ArmDataMap, DeviceClickcallBack)
  await loadAllModels(agvData, AGVDataMap, DeviceClickcallBack)

  await loadAllModels(xingjiaType01Data, XJDataMap, DeviceClickcallBack)
  await loadAllModels(xingjiaType02Data, XJDataMap2, DeviceClickcallBack)

  await loadAllModels(xingjiaTypeTempData, XJDataMapTemp, DeviceClickcallBack)

  await loadAllModels(GTYXData, GYTXDataMap, DeviceClickcallBack)

  await loadAllModels(PogoData, PogoDataMap, DeviceClickcallBack)

  await LoadModels()

  await getCollectData()

  window.sandbox.logger.log('初始化设备完毕...')
  InitSocket(socketCallBack)
  // console.log(sceneModelMap)
}
// 加载场景lod模型
async function LoadModels () {
  // const resp = await fetch(`${window.modelUrl}json/directory_treeTestNew.json`);
  // if (!resp) {
  //   return;
  // }
  // const res = await resp.json();

  modelUrls = generateCZMLFromJSON(directory_treeData)
  // 创建所有加载任务的Promise数组  map 中的每个回调函数（因为是 async）都会返回一个 Promise

  const startTime = performance.now() // 记录开始时间
  // await GetAllModelsFileSize(modelUrls)

  const loadPromises = modelUrls.map(async (item) => {
    const hamdlemodel = await new GCMap.GltfModel({
      sandbox: window.sandbox,
      url: window.modelUrl + item.dataPath,
      isChangeMatMetal: true,
      isAddScene: false,
      isCastShadow: true,
      isReceiveShadow: false,
      position: modelPos,
      enableClearCoatMat: item.enableClearCoatMat || false
      // metalness: 0.7,
      // roughness: 0.9
    })
    // ShowClickEffect(model.scene);
    CreateLod(item, hamdlemodel.model)
    // hamdlemodel.setMarerialOpacity(0.5)
    return hamdlemodel.model
  })
  try {
    // 等待所有模型加载完成
    const loadedModels = await Promise.all(loadPromises)
    const endTime = performance.now() // 记录结束时间
    const duration = endTime - startTime // 计算耗时(毫秒)
    window.sandbox.logger.log(
      `模型加载完成，共加载 ${loadedModels.length} 个模型，耗时 ${(
        duration / 1000
      ).toFixed(2)} 秒`
    )
    loadHighModels()
  } catch (error) {
    console.error('模型加载失败:', error)
  }
}
// 加载精模
async function loadHighModels () {
  if (!window.isOnLod) return
  const startTime = performance.now() // 记录开始时间
  window.sandbox.logger.log('执行加载完成后的操作')
  // 例如：隐藏加载进度条、开始动画等
  let count = 0
  window.sandbox.logger.log('开始加载Draco压缩精模')
  const loadPromises = modelUrls.map(async (item) => {
    let modelUrl = item.dataPath.includes('low')
      ? item.dataPath.replace('low', 'high')
      : item.dataPath // 如果不包含 low，则保持原样
    modelUrl = window.modelUrl + modelUrl
    const size = await getFileSize(modelUrl)
    const modelSize = formatFileSize(size, 2)
    if (size > 200 * 1024 * 1024) {
      console.warn(`大模型警告:${modelSize}模型地址:${modelUrl}`)
    }
    const { model } = await new GCMap.GltfModel({
      sandbox: window.sandbox,
      url: modelUrl,
      isChangeMatMetal: true,
      isAddScene: false,
      isCastShadow: true,
      isReceiveShadow: false,
      position: modelPos
    })

    count++
    // window.sandbox.logger.log(count + "/" + modelUrls.length + "模型大小:" + modelSize);
    // ShowClickEffect(model);
    if (lodMap.has(item.dataPath)) {
      const boundingBox = new GC.Box3().setFromObject(model.scene)
      const center = boundingBox.getCenter(new GC.Vector3())
      const lod = lodMap.get(item.dataPath)
      lod.addLevel(model.scene, 0) // 50+单位距离显示低模
      model.scene.position.sub(center)
    } else {
      console.error('Error:', '不存在', item)
    }
    return model // 返回加载完成的模型
  })

  try {
    // 等待所有模型加载完成
    const loadedModels = await Promise.all(loadPromises)

    const endTime = performance.now() // 记录结束时间
    const duration = endTime - startTime // 计算耗时(毫秒)
    window.sandbox.logger.log(
      `精模加载完成，共加载 ${loadedModels.length} 个模型，耗时 ${(
        duration / 1000
      ).toFixed(2)} 秒`
    )
  } catch (error) {
    console.error('模型加载失败:', error)
  }
}
function handleDoubleClick (e) {
  // console.log("点击特效", e);
  if (boxEffect) {
    boxEffect.off('doubleClick', handleDoubleClick)
    boxEffect.destroy()
    boxEffect = null
    currentSelectModel = null
  }
}
function generateCZMLFromJSON (jsonData) {
  window.sandbox.logger.log('加载配置文件...')
  const templUrls = []
  // 递归遍历JSON结构
  function traverse (node, path = '') {
    if (node.label.endsWith('.glb')) {
      // const modelName = node.label.replace(".glb", "");
      // const modelFullUrl = baseUrl + node.dataPath;
      templUrls.push(node)
    }

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      node.children.forEach((child) => {
        traverse(child, path + '/' + node.label)
      })
    }
  }

  // 开始遍历
  jsonData.forEach((rootNode) => {
    traverse(rootNode)
  })
  return templUrls
}

function CreateLod (item, model) {
  const lod = new GC.LOD()
  const boundingBox = new GC.Box3().setFromObject(model.scene)
  const center = boundingBox.getCenter(new GC.Vector3())
  const size = boundingBox.getSize(new GC.Vector3()).length()
  const lowDist = size * GeometryError
  // const lowDist = 5
  model.scene.position.sub(center)
  lod.addLevel(model.scene, lowDist) // 50+单位距离显示低模
  lod.position.copy(center)
  window.sandbox.scene.add(lod)
  if (sceneModelMap.has(item.belongArea)) {
    sceneModelMap.get(item.belongArea).push(lod)
  } else {
    sceneModelMap.set(item.belongArea, [lod])
  }

  if (!lodMap.has(item.dataPath)) {
    lodMap.set(item.dataPath, lod)
  } else {
    console.error('Error in CreateLod:', '已存在', item)
  }
  // const currrentshowmodel = lod.levels[lod._currentLevel].object;
  onEvent(lod, 'doubleClick', (e) => {
    window.sandbox.logger.log('材质名称', e.pickedObject.material.name)
    window.sandbox.logger.log('点击', item.dataPath, lod._currentLevel)
    // const currrentshowmodel = lod.children[lod._currentLevel]
    // currrentshowmodel.changeMaterialColor()
    // currrentshowmodel.ResetMaterial()
    // ShowClickEffect(item, currrentshowmodel);
    // ShowBoundingBox(item, currrentshowmodel);
    // outLine.add(currrentshowmodel);
    // addTransformControlsMesh02(currrentshowmodel);
  })
}

function onEvent (overlay, eventType, callbackFunc) {
  const handlerOfType = window.sandbox.eventMap.get(eventType)
  if (handlerOfType) {
    if (!handlerOfType.has(overlay)) {
      handlerOfType.set(overlay, [])
    }
    handlerOfType.get(overlay).push(callbackFunc)
  } else {
    console.error('事件类型错误')
  }
}

async function ShowClickEffect (item, model) {
  console.log('创建特效')
  // 如果点击的是当前已选中的模型
  if (currentSelectModel === item.dataPath) {
    // 如果已有特效，则销毁
    if (boxEffect) {
      boxEffect.destroy()
      boxEffect = null
    }
    currentSelectModel = null
    return
  }

  // 如果点击的是不同模型，先销毁旧特效
  if (boxEffect) {
    boxEffect.destroy()
    boxEffect = null
  }

  // 创建新特效
  currentSelectModel = item.dataPath
  const boundingBox = new GC.Box3().setFromObject(model)
  const size = boundingBox.getSize(new GC.Vector3())
  const center = boundingBox.getCenter(new GC.Vector3())

  boxEffect = await new GCMap.BoxEffect({
    sandbox: window.sandbox,
    speed: 0.5,
    position: center,
    scale: { ...size },
    width: 0.5
  })

  // 添加双击事件监听
  boxEffect.on('doubleClick', handleDoubleClick)
}
function ShowBoundingBox (item, model) {
  const boundingBox = new GC.Box3().setFromObject(model)
  const size = boundingBox.getSize(new GC.Vector3())
  const center = boundingBox.getCenter(new GC.Vector3())

  // 如果点击的是当前已选中的模型
  if (currentSelectModel === item.dataPath) {
    // 如果已有包围盒，则销毁
    if (boxHelper) {
      window.sandbox.scene.remove(boxHelper)
      boxHelper = null
    }
    currentSelectModel = null
    return
  }

  // 如果点击的是不同模型
  if (boxHelper) {
    // 更新包围盒数据
    boxHelper.box.copy(boundingBox)
  } else {
    // 创建新包围盒
    boxHelper = new GC.Box3Helper(boundingBox, 0xffff00)
    window.sandbox.scene.add(boxHelper)
  }

  currentSelectModel = item.dataPath
}
function ShowOutLineEffect2 (model) {
  // 如果点击的是不同模型
  outLine2.clear()
  outLine.clear()
  outLine.add(model)
  // currentSelectModel = item.id
}

function ShowOutLineEffect (item, model) {
  // 如果点击的是当前已选中的模型
  if (currentSelectModel === item.id) {
    // 如果已有包围盒，则销毁
    // outLine.clear()
    currentSelectModel = null
    return
  }
  if (!outLine) return
  // 如果点击的是不同模型
  outLine2.clear()
  outLine.clear()
  outLine.add(model)
  currentSelectModel = item.id
}

function createProgressCallback (modelUrl) {
  return (xhr) => {
    // window.sandbox.logger.log(`[${modelUrl}] 加载进度: ${((xhr.loaded / xhr.total) * 100).toFixed(2)}%`);
    window.sandbox.logger.log(
      `${modelUrl}已加载: ${formatFileSize(xhr.loaded)} / ${formatFileSize(xhr.total)}`
    )
  }
}
async function GetAllModelsFileSize (loadmodelUrls) {
  let Totalsize = 0
  const loadPromises = loadmodelUrls.map(async (item) => {
    const modelUrl = window.modelUrl + item.dataPath
    const size = await getFileSize(modelUrl)
    const modelSize = formatFileSize(size, 2)
    Totalsize = Totalsize + size
    if (size > 200 * 1024 * 1024) {
      console.warn(`大模型警告:${modelSize}模型地址:${modelUrl}`)
    }
    return modelSize
  })

  try {
    // 等待所有模型加载完成
    const AllModelsSize = await Promise.all(loadPromises)
    window.sandbox.logger.log(
      '所有模型大小获取完成',
      '数量:',
      AllModelsSize.length,
      '尺寸:',
      formatFileSize(Totalsize)
    )
  } catch (error) {
    console.error('模型尺寸获取失败:', error)
  }
}

function formatFileSize (bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const dm = decimals < 0 ? 0 : decimals
  const sizes = ['Bytes', 'KB', 'MB', 'GB']

  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}
async function getFileSize (url) {
  try {
    const response = await fetch(url, { method: 'HEAD' })
    const contentLength = response.headers.get('Content-Length')
    return contentLength ? parseInt(contentLength) : 0
  } catch (error) {
    console.error('获取文件大小失败:', error)
    return 0
  }
}

// 设置鼠标移动旋转范围
function SetControls () {
  const controls = window.sandbox.controls
  // 自动旋转
  controls.autoRotate = false
  controls.enableZoom = true
  // 设置阻尼
  controls.enableDamping = true
  controls.dampingFactor = 0.5

  // 设置是否围绕鼠标中心点旋转 false为围绕鼠标旋转
  controls.screenSpacePanning = false

  // 限制距离
  controls.minDistance = 0
  controls.maxDistance = 100

  // controls.minAzimuthAngle = -Math.PI / 4; // -45度
  // controls.maxAzimuthAngle = Math.PI / 4; // 45度

  // 限制垂直旋转角度（极角，单位：弧度）
  controls.minPolarAngle = 0 // 45度（从顶部算起）
  controls.maxPolarAngle = (Math.PI * 3) / 7 // 135度（从顶部算起）

  controls.enablePan = true // 默认 true（允许水平移动）
  // 限制水平移动范围
  controls.minTargetRadius = 0
  controls.maxTargetRadius = 50

  controls.minZoom = 0
  controls.maxZoom = 10
}

async function loadAllModels (ModelData, modelMap, ClickcallBack) {
  // 使用for...of循环按顺序处理，确保前一个模型的加载完成后再处理下一个
  for (const item of ModelData) {
    try {
      // window.sandbox.logger.log('开始处理模型:', item.dataPath);
      let handleM = null

      // 检查是否已经有加载完成的模型
      if (AllModelTypeMap.has(item.dataPath)) {
        const handleTemp = AllModelTypeMap.get(item.dataPath)
        handleM = await GetCloneModel(item, handleTemp)
        // window.sandbox.logger.log("克隆物体:", item.dataPath);
      }
      // 检查是否正在加载中
      else if (loadingPromises.has(item.dataPath)) {
        window.sandbox.logger.log('等待已开始的加载:', item.dataPath)
        await loadingPromises.get(item.dataPath)

        // 加载完成后应该已经存入AllModelTypeMap
        const handleTemp = AllModelTypeMap.get(item.dataPath)
        handleM = await GetCloneModel(item, handleTemp)
      }
      // 需要全新加载
      else {
        //  window.sandbox.logger.log("加载物体:", item.dataPath);
        // 创建并存储加载Promise
        const loadPromise = new GCMap.GltfModel2({
          itemData: item,
          sandbox: window.sandbox,
          url: window.modelUrl + item.dataPath,
          isChangeMatMetal: true,
          isAddScene: true,
          isCastShadow: item.isCastShadow || true,
          isReceiveShadow: item.isReceiveShadow,
          position: item.position,
          rotation: item.rotation,
          label: item.id,
          fontOffect: item.fontOffect || { x: 0, y: 0, z: 0 },
          markOffect: item.markOffect || { x: 0, y: 3, z: 0 },
          isShowLable: item.isShowLable || false,
          enableClearCoatMat: item.enableClearCoatMat || false
        }).then((loadedModel) => {
          AllModelTypeMap.set(item.dataPath, loadedModel)
          // window.sandbox.logger.info("存储模型:", item.dataPath);
          return loadedModel
        })

        loadingPromises.set(item.dataPath, loadPromise)
        handleM = await loadPromise

        // 加载完成后从loadingPromises移除
        loadingPromises.delete(item.dataPath)
      }

      modelMap.set(item.id, handleM)
      if (item.belongArea) {
        if (sceneModelMap.has(item.belongArea)) {
          sceneModelMap.get(item.belongArea).push(handleM)
        } else {
          sceneModelMap.set(item.belongArea, [handleM])
        }
      }
      // 事件处理和其他逻辑...
      handleM.on('doubleClick', (e) => {
        window.sandbox.logger.log('材质名称', e.pickedObject.material.name, e.pickedObject.material)
        window.sandbox.logger.log('模型', item, handleM)
        console.log(item)
        ShowOutLineEffect(item, e.rootNode)
        if (item.idDevice) {
          if (handleModel) {
            handleModel.isclick = false
          }
        }
        handleModel = handleM
        if (item.idDevice) {
          handleModel.isclick = true
        }

        articulations.value =
          handleModel.model.userData.gltfExtensions.AGI_articulations.articulations
        ClickcallBack(e, item)
        // handleM.updateMarkImage('11111')
        // handleM.markType=2
        // handleM.showMark()
        // console.log(articulations.value);
        // addTransformControlsMesh02(handleM.overlay);
      })

      handleM.on('mouseenter', (e) => {
        if (!item.idDevice) return
        if (handleM.isclick) return
        console.log('进入', item.id)
        outLine2.add(e.rootNode)
      })
      handleM.on('mouseleave', (e) => {
        if (!item.idDevice) return
        if (handleM.isclick) return
        console.log('离开', item.id)
        outLine2.remove(e.rootNode)
      })
      if (item.type === 'fixture' || item.type === 'fixture2') {
        let banzi = null
        if (handleM.model.scene) {
          banzi = handleM.model.scene.getObjectByName('banzi')
        } else {
          banzi = handleM.model.getObjectByName('banzi')
        }
        if (item.isHasBanzi) {
          banzi.visible = true
        } else {
          banzi.visible = false
        }
      }
      setTimeout(() => {
        if (item.originaOffectlPose) {
          updatedhandleOriginData(item.originaOffectlPose, handleM)
        }
      }, 0)
      setTimeout(() => {
        updatedhandleData(item.pose, handleM, false)
      }, 0)
    } catch (error) {
      window.sandbox.logger.error(`加载模型 ${item.dataPath} 出错:`, error)
    }
  }
}

async function GetCloneModel (item, handleTemp) {
  const handle = await new GCMap.GltfModelClone2({
    sandbox: window.sandbox,
    itemData: item,
    isChangeMatMetal: true,
    isAddScene: true,
    isCastShadow: item.isCastShadow || true,
    isReceiveShadow: item.isReceiveShadow,
    position: item.position,
    rotation: item.rotation,
    gltfModel: handleTemp,
    label: item.id,
    fontOffect: item.fontOffect || { x: 0, y: 0, z: 0 },
    markOffect: item.markOffect || { x: 0, y: 3, z: 0 },
    isShowLable: item.isShowLable || false,
    enableClearCoatMat: item.enableClearCoatMat || false
  })
  return handle
}

async function loadSimpleModels (ModelData) {
  const loadPromises = ModelData.map(async (item) => {
    const handleM = await new GCMap.GltfModel({
      sandbox: window.sandbox,
      url: window.modelUrl + item.dataPath,
      isChangeMatMetal: true,
      isAddScene: true,
      isCastShadow: item.isCastShadow,
      isReceiveShadow: item.isReceiveShadow,
      position: item.position,
      rotation: item.rotation,
      metalness: 0.7,
      roughness: 0.9
      // enableClearCoatMat: item.enableClearCoatMat || false
    })

    if (sceneModelMap.has(item.belongArea)) {
      sceneModelMap.get(item.belongArea).push(handleM)
    } else {
      sceneModelMap.set(item.belongArea, [handleM])
    }

    handleM.on('doubleClick', (e) => {
      window.sandbox.logger.log('材质名称', e.pickedObject.material.name)
      // window.sandbox.logger.log("模型", e);
      // console.log(e,colorToHex(e.pickedObject.material.color))
      //  handleM.changeMaterialColor()
      // outLine.add(e.rootNode);
      // handleModel = handleM;
      // articulations.value =
      //   handleModel.model.userData.gltfExtensions.AGI_articulations.articulations;
      // addTransformControlsMesh02(handleM.model.scene);
    })
    return handleM
  })

  return await Promise.all(loadPromises)
}

// 更新原点
function updatedhandleOriginData (obj, handleM) {
  Object.keys(obj).forEach((key) => {
    handleM.setArticulationOriginData(key.trim(), obj[key] - 0)
  })
}
// 聚焦区域可视化
function focusAreaModel (areaName) {
  freshXJBelong(areaName)
  sceneModelMap.forEach((models, key) => {
    models.forEach(model => {
      let currentShowModel = null
      if (model.type === 'LOD') {
        currentShowModel = model.children[model._currentLevel]
      } else {
        currentShowModel = model
      }

      if (key === areaName) {
        // 聚焦区域 → 恢复原始材质
        currentShowModel.ResetMaterial()
        currentShowModel.createMark?.()
      } else {
        // 非聚焦区域 → 半透明
        currentShowModel.setMarerialOpacity(0.1, '#2e547b') // #2e547b
      }
    })
  })
}
// 恢复所有材质
function ResetAllmodelMats () {
  sceneModelMap.forEach((models, key) => {
    models.forEach(model => {
      let currentShowModel = null
      if (model.type === 'LOD') {
        currentShowModel = model.children[model._currentLevel]
      } else {
        currentShowModel = model
      }
      currentShowModel.ResetMaterial()
      currentShowModel.destroyMark?.()
    })
  })
}

// 修改材质颜色
function changeModelMats () {
  sceneModelMap.forEach((models, key) => {
    models.forEach(model => {
      let currentShowModel = null
      if (model.type === 'LOD') {
        currentShowModel = model.children[model._currentLevel]
      } else {
        currentShowModel = model
      }
      currentShowModel.changeMaterialColor()
    })
  })
}

function destroyModels () {
  models?.forEach((model) => {
    if (typeof model?.destroy === 'function') {
      model.destroy() // 确保 destroy 是函数才调用
    } else if (model?.isObject3D) {
      window.sandbox?.scene?.remove(model)
    }
  })
  models = []

  sceneModelMap.forEach((lods, key) => {
    lods.forEach(lod => {
      if (typeof lod?.destroy === 'function') {
        lod.destroy() //
      } else {
        window.sandbox?.scene?.remove(lod)
      }
    })
  })
  sceneModelMap.clear()

  destroyAllModels()

  ArmDataMap.clear()
  AGVDataMap.clear()
  if (socket !== null) {
    socket.Close()
  }
  if (boxEffect !== null) {
    boxEffect.destroy()
    boxEffect = null
  }
  if (outLine) {
    outLine.destroy()
    outLine2.destroy()
    outLine = null
  }
}
function clearOutLine () {
  if (handleModel) {
    handleModel.isclick = false
    handleModel = null
  }
  currentSelectModel = null
  outLine.clear()
}
async function freshXJBelong (areaName) {
  const { data: res } = await getInfoFuzzy({ modelId: 'fixtureInfo' })
  const data = res.data.map(item => {
    const belong = JSON.parse(item.collectValue)['型架当前位置']
    const xjData = XJPostionData.find(xjData => belong.includes(xjData.stationName))
    const index = parseInt(item.modelId.match(/(\d+)$/)[0])
    if (index <= 5) {
      item.modelId = 'fixture1-P0' + index
    } else if (index === 10) {
      item.modelId = 'fixture2-P' + index
    } else {
      item.modelId = 'fixture2-P0' + index
    }
    if (xjData === undefined) {
      const xingjiaType = index <= 5 ? xingjiaType01Data : xingjiaType02Data
      const xj = xingjiaType.find((item2) => item2.id === item.modelId)
      return {
        modelId: item.modelId,
        belong: xj.belongArea
      }
    } else {
      return {
        modelId: item.modelId,
        belong: xjData.region
      }
    }
  })

  data.forEach(item => {
    const xjMap = item.modelId.includes('fixture1') ? XJDataMap : XJDataMap2
    const xjData = xjMap.get(item.modelId)
    if (xjData) {
      item.model = xjData
    }
  })
  const scenexjModelMap = new Map()
  data.forEach(item => {
    if (scenexjModelMap.has(item.belong)) {
      scenexjModelMap.get(item.belong).push(item.model)
    } else {
      scenexjModelMap.set(item.belong, [item.model])
    }
  })
  scenexjModelMap.forEach((models, key) => {
    if (key === areaName) {
      models.forEach(model => {
        model.ResetMaterial()
      })
    } else {
      models.forEach(model => {
        model.setMarerialOpacity(0.1, '#2e547b') // #2e547b()
      })
    }
  })
  console.log('data', scenexjModelMap)
}

function HighModel (modelid) {
  for (const models of sceneModelMap.values()) {
    const model = models.find(item => item?._itemData?.id === modelid)
    if (model) {
      if (model.model.scene) {
        ShowOutLineEffect2(model.model.scene)
      } else {
        ShowOutLineEffect2(model.model)
      }
      return // 已找到，直接退出
    }
  }
}

export default { HighModel, changeModelMats, ResetAllmodelMats, focusAreaModel, Create3DLable, InitScene, destroyModels, clearOutLine }
